package fuwuqi;
import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.Key;

public class service{
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        OutputStream os = null;
        InputStream is = null;
        MyDC np = new MyDC();
        //端口号

        int port = 2333;
        try {
            //建立

            serverSocket = new ServerSocket(port);
            System.out.println("连接成功");
            //获得

            socket = serverSocket.accept();
            System.out.println("连接成功");
            //客户端内容

            is = socket.getInputStream();
            byte[] b = new byte[2048];
            int n = is.read(b);
            System.out.println("接收数据成功");
            //导出

            String message=new String(b,0,n);
            System.out.println("客户端的数据内容：" + message);


                //1.读取文件中的密钥
                File file = new File("CWC-LCH.txt");
                InputStream inputStream = new FileInputStream(file);//文件内容的字节流
                InputStreamReader inputStreamReader= new InputStreamReader(inputStream); //得到文件的字符流
                BufferedReader bufferedReader=new BufferedReader(inputStreamReader); //放入读取缓冲区
                String readd="";
                StringBuffer stringBuffer=new StringBuffer();
                while ((readd=bufferedReader.readLine())!=null) {
                    stringBuffer.append(readd);
                }
                inputStream.close();
                String keystr=stringBuffer.toString();
                System.out.println(keystr+" -----> key读取成功");  //读取出来的key是编码之后的 要进行转码

                //2.通过读取到的key  获取到key秘钥对象
                byte[] keybyte= HexBin.decode(keystr);
                DESedeKeySpec deSedeKeySpec=new DESedeKeySpec(keybyte);
                SecretKeyFactory secretKeyFactory=SecretKeyFactory.getInstance("DESede");
                Key key= secretKeyFactory.generateSecret(deSedeKeySpec); //获取到key秘钥

                //3.进行解密
                Cipher cipher=Cipher.getInstance("DESede/ECB/PKCS5Padding");
                cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result= cipher.doFinal(message);
            System.out.println("接收方进行解密："+new String(result));

            String re= np.evaluate(message)+"";
            //客户端反馈

            //os = socket.getOutputStream();

            //os.write(b,0,n);

            os = socket.getOutputStream();
            os.write(re.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try{
                //关闭流和连接

                os.close();
                is.close();
                socket.close();
                serverSocket.close();
            }catch(Exception e){}
        }
    }
}